#include "audiomanager.h"

AudioManager::AudioManager()
{
    connect(this, SIGNAL(readyRead()), SLOT(treadData()));
    connect(&m_audioEngine, SIGNAL(senddata(QByteArray*)), this, SLOT(sendRecord(QByteArray*)));
    connect(this, SIGNAL(sendSound(QByteArray*)), &m_audioEngine, SLOT(recv_data(QByteArray*)));
    m_startRecord = false;
}

void AudioManager::startRecord()
{
    m_audioEngine.startPaRecorder();
    m_audioEngine.startPaPlayback();
    m_startRecord = true;
}


void AudioManager::sendRecord(QByteArray* block)
{
    QTextStream out(this);
    qDebug() << "Data send " << block;
    out << block;
}

void AudioManager::treadData()
{
    if(!m_startRecord)
        startRecord();
    while (hasPendingDatagrams()) {
        QByteArray * datagram = new QByteArray();
        datagram->resize(pendingDatagramSize());
        readDatagram(datagram->data(), datagram->size());
        emit sendSound(datagram);
    }
}
void AudioManager::startListen()
{
    bind(QHostAddress::Any, 1337);
    qDebug() << "Start listen";
}

bool AudioManager::connectPeer(QString addr, qint32 port)
{
    if(addr.isEmpty() || port == 0)
        return false;

    if(state() != UnconnectedState)
        abort();
    connectToHost(addr, port);
    if(state() != UnconnectedState)
        return true;
    return false;
}


